package com.business.form.action;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.business.base.BaseController;
import com.business.base.Pager;
import com.business.form.po.FormBean;
import com.business.form.po.FormControlBean;
import com.business.form.service.FormControlService;
import com.business.form.service.FormParamsService;
import com.business.form.service.FormParamsValueService;
import com.business.form.service.FormSaveService;
import com.business.form.service.FormService;
import com.common.ErrorLog;
import com.common.NumberProcess;
import com.common.RenderPage;
import com.common.StringProcess;
import com.common.utils.SpringContextHolder;


/**
 * @author jpx 
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping(value="/form/formControl")
public class FormControlController{
	
	@Autowired
	FormControlService formControlService;
	
	@Autowired
	FormService formService;
	
	@Autowired
	FormSaveService formSaveService;
	
	@Autowired
	FormParamsService formParamsService;

	
	@RequestMapping(value="/nav")
	public String nav(HttpServletRequest request,ModelMap model) {
				
		StringBuilder leftUrlParams=new StringBuilder();
		leftUrlParams.append("dataMapper=form.form.selectTree");
		leftUrlParams.append("&");
		leftUrlParams.append("searchMapper="+URLEncoder.encode("{\"pageClassifyCode\":\"bdy\"}"));
		leftUrlParams.append("&");
		leftUrlParams.append("clickScript="+URLEncoder.encode("parent.document.getElementById('right').src='../../form/formControl/list?nodeId=url.NodeId&parentNodeId=url.ParentNodeId';"));
		model.put("leftUrlParams", leftUrlParams.toString());
		
		model.put("rightUrl", "../../form/formControl/list");
		
		return "/components/navpage/nav";
	}
	
	@RequestMapping(value="/list")
	public String list(HttpServletRequest request,ModelMap model) {
		
		String nodeId=StringProcess.getRequest(request.getParameter("nodeId"), "");
		String parentNodeId=StringProcess.getRequest(request.getParameter("parentNodeId"), "");
		
		model.put("nodeId", nodeId);
		model.put("parentNodeId", parentNodeId);
		
		return "/form/formControl/list";
	}

	@RequestMapping({ "/detail" })
	public String detail(HttpServletRequest request, ModelMap model) {
		try{

		    String formControlId = StringProcess.getRequest(request.getParameter("formControlId"), "");
		    String nodeId=StringProcess.getRequest(request.getParameter("nodeId"), "");
			String parentNodeId=StringProcess.getRequest(request.getParameter("parentNodeId"), "");

			//初始化控件
			String formId="";
			String formTabId="";	    
		    
			
			String action = "";
			int formControlType=0;
			FormControlBean bean=new FormControlBean();
			if (formControlId.length() == 0) {
				action = "insert";
			    formControlId = StringProcess.getUUID();
				bean.setFormControlId(formControlId);
				
				if(parentNodeId.length()>0 || nodeId.length()>0)
				{
					if(parentNodeId.equals("0"))
				    {
				    	formId=nodeId;
				    }
				    else
				    {
				    	formId=parentNodeId;
				    	formTabId=nodeId;
				    }
				}
				bean.setFormId(formId);
				bean.setFormTabId(formTabId);
			} else {
				action = "update";
				bean=formControlService.getBeanByKeyId(formControlId);
				formControlType=bean.getFormControlType();
				formId=bean.getFormId();
			}
			

			//参数列
			if(formControlType>0)
			{
				Map<String, Object> paramMap = new HashMap<String, Object>();
				int objectType=convertByFormControlType(formControlType);
				paramMap.put("objectType",objectType);
				paramMap.put("objectId",formControlId);
				List<Map<String, Object>> listFormParams = formParamsService.select(paramMap);
				
				Map<String, Object> itemData = new HashMap<String, Object>();
				itemData.put("ObjectType", objectType);
				itemData.put("ParamsText", "表单控件唯一编号");
				itemData.put("ValueType", "1");
				itemData.put("ObjectId", "");
				itemData.put("ParamsValueId", "");
				itemData.put("IsDepend", "0");
				itemData.put("ParamsCode", "ID");
				itemData.put("ParamsId", "ID");
				itemData.put("ParamsValue", "e"+objectType+"_"+formControlId);
				itemData.put("ReadOnly", "1");
				listFormParams.add(0, itemData);
				
				BaseController.ProcessParams(model, listFormParams);
			}
						
			
			
			String formName="";
			if(bean.getFormId().length()>0 || bean.getFormTabId().length()>0)
			{
				Map<String,Object> paramMap=new HashMap<String, Object>();
				paramMap.put("pageClassifyCode", "bdy");
				boolean useTab=false;
				if(bean.getFormTabId().length()>0)
				{
					paramMap.put("formId", bean.getFormId());
					paramMap.put("formTabId", bean.getFormTabId());
					useTab=true;
				}
				else
				{
					paramMap.put("formId", bean.getFormId());
				}
				List<Map<String,Object>> list=formService.selectTree(paramMap);
				for(int i=0;i<list.size();i++)
				{
					Map<String,Object> item=list.get(i);
					if(useTab && item.get("ParentNodeText").toString().length()==0)
					{
						continue;
					}
					else if(useTab==false && item.get("ParentNodeText").toString().length()>0)
					{
						continue;
					}
					
					if(item.get("ParentNodeText").toString().length()==0)
					{
						formName=item.get("NodeText").toString();
					}
					else
					{
						formName=item.get("ParentNodeText").toString()+"."+item.get("NodeText").toString();
					}
				}
			}
			
			//读取formSave-form
			if(formId.length()>0)
			{
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("formId",formId);
				paramMap.put("saveType",1);
				List<Map<String, Object>> listFormSave = formSaveService.select(paramMap);
				String parentTableId="";
				for(int i=0;i<listFormSave.size();i++)
				{
					if(i>0)
					{
						parentTableId+=",";
					}
					parentTableId+=listFormSave.get(i).get("SaveTableId");
				}
				model.put("parentTableId", parentTableId);
			}
			
			//读取formSave-Control
			if(formControlId.length()>0)
			{
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap = new HashMap<String, Object>();
				paramMap.put("formId",formId);
				paramMap.put("formControlId",formControlId);
				paramMap.put("saveType",2);
				List<Map<String, Object>> listFormSave = formSaveService.select(paramMap);
				String saveTableId="";
				String saveTableName="";
				String saveFieldId="";
				String saveFieldName="";
				for(int i=0;i<listFormSave.size();i++)
				{
					if(i>0)
					{
						saveTableId+=",";
						saveTableName+=",";
						saveFieldId+=",";
						saveFieldName+=",";
					}
					saveFieldId+=listFormSave.get(i).get("SaveFieldId");
					saveFieldName+=(listFormSave.get(i).get("SaveTableName")+"."+listFormSave.get(i).get("SaveFieldName"));
					saveTableId+=listFormSave.get(i).get("SaveTableId");
					saveTableName+=listFormSave.get(i).get("SaveTableName");
				}
				model.put("saveFieldId", saveFieldId);
				model.put("saveFieldName", saveFieldName);
				model.put("saveTableId", saveTableId);
				model.put("saveTableName", saveTableName);
			}

			

			model.put("action", action);
			model.put("bean", bean);
			model.put("formName", formName);
			
		}catch(Exception e){
			ErrorLog.OnWrite(e);
		}
		
		return "/form/formControl/detail";
	}
	
	private int convertByFormControlType(int formControlType)
	{		
		return formControlType;
	}
	
	@RequestMapping("/getTableByFormId")
	public void getTableByFormId(HttpServletResponse response,String formId) {
		String ret="";
		
		if(formId.length()>0)
		{
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap = new HashMap<String, Object>();
			paramMap.put("formId",formId);
			paramMap.put("saveType",1);
			List<Map<String, Object>> listFormSave = formSaveService.select(paramMap);
			String saveTableId="";
			for(int i=0;i<listFormSave.size();i++)
			{
				if(i>0)
				{
					saveTableId+=",";
				}
				saveTableId+=listFormSave.get(i).get("SaveTableId");
			}
			ret=saveTableId;
		}
		
		RenderPage.JsonByString(response, ret);
	}
	
	@RequestMapping("/query")
	public void query(Integer pageIndex, Integer pageSize, HttpServletRequest request, HttpServletResponse response,
			ModelMap map) {
			
		try{
			Map<String, Object> search = new HashMap<String, Object>();
			String formControlTitle = request.getParameter("txtFormControlTitle");
			if(StringUtils.isNotEmpty(formControlTitle)){
				search.put("formControlTitle", "%"+formControlTitle+"%");
			}
			
			//筛选条件
			String nodeId=StringProcess.getRequest(request.getParameter("nodeId"), "");
			String parentNodeId=StringProcess.getRequest(request.getParameter("parentNodeId"), "");
			if(nodeId.length()>0 || parentNodeId.length()>0)
			{
				
				if(parentNodeId.equals("0"))
				{
					if(StringUtils.isNotEmpty(nodeId)){
						search.put("formId", nodeId);
					}
				}
				else
				{
					if(StringUtils.isNotEmpty(parentNodeId)){
						search.put("formId", parentNodeId);
					}
					if(StringUtils.isNotEmpty(nodeId)){
						search.put("formTabId", nodeId);
					}
				}
				
				Pager<Map<String, Object>> result = formControlService.selectPage(pageIndex,pageSize,search);
				
				int resultCount = result.getList().size();
				for (int i = 0; i < resultCount; i++) {
					Map<String, Object> item = result.getList().get(i);
					
					item = BaseController.AddChangeRow(SpringContextHolder.getBean(FormControlService.class), result.getList(), item, result.getTotal(), pageIndex, i, result.getPages(), pageSize, resultCount,"FormControlId","OrderNumber", search);
				}
				
				RenderPage.JsonByObject(response, result);
			}
			
		}catch(Exception e){
			ErrorLog.OnWrite(e);
		}
		
	}
	
	
	@RequestMapping(params = "method=save", method = RequestMethod.POST)
	public void save(HttpServletRequest request, HttpServletResponse response) {

		try {
			
			String action = request.getParameter("action");
			String formControlId = request.getParameter("txtFormControlId");
			String formControlTitle = request.getParameter("txtFormControlTitle");
			String formId = request.getParameter("hidFormId");
			String formTabId = request.getParameter("hidFormTabId");
			String groupId = request.getParameter("txtGroupId");
			String formControlType = request.getParameter("lstFormControlType");
			String widthType = request.getParameter("rdoWidthType");
			String heightNumber = request.getParameter("lstHeightNumber");
			String orderNumber = request.getParameter("txtOrderNumber");
			
			
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("formControlId", formControlId);
			model.put("formControlTitle", formControlTitle);
			model.put("formId", formId);
			model.put("formTabId", formTabId);
			model.put("groupId", groupId);
			model.put("formControlType", formControlType);
			model.put("widthType", widthType);
			model.put("heightNumber", heightNumber);
			model.put("orderNumber", orderNumber);

			if (action.equals("insert")) {
				formControlService.insert(model);
			} else if (action.equals("update")) {
				formControlService.update(model);
			}
			
			//FormSave
			String saveFieldId = request.getParameter("hidSaveFieldId");
			String saveFieldName = request.getParameter("txtSaveFieldName");
			String saveTableId = request.getParameter("hidSaveTableId");
			String saveTableName = request.getParameter("hidSaveTableName");
			saveFormSave(saveTableId,saveTableName,saveFieldId,saveFieldName,formId,formControlId);
			
			
			//FormParams
			String formParamIds=request.getParameter("hidFormParamIds");
			List<Map<String,Object>> listFormParams=new ArrayList<Map<String, Object>>();
			String[] formParamIdArray=formParamIds.split(",");
			for(int i=0;i<formParamIdArray.length;i++)
			{
				Map<String,Object> itemFormParams=new HashMap<String, Object>();
				String paramsId=formParamIdArray[i];
			
				itemFormParams.put("ParamsValueId", request.getParameter("cv_"+paramsId));
				itemFormParams.put("ParamsId", paramsId);
				itemFormParams.put("ObjectId", formControlId);
				itemFormParams.put("ParamsValue", request.getParameter("c_"+paramsId));
				listFormParams.add(itemFormParams);
			}
			saveParams(listFormParams,formControlId,NumberProcess.convertToNumber(formControlType));

			
			
			
			//保存FormData
			FormBean formBean=formService.getBeanByKeyId(formId);
			String formData=formBean.getFormData();
			if(formData.length()>0)
			{
				Map<String,Object> formDataMap=JSON.parseObject(formData, new TypeReference<Map<String,Object>>(){});
				
				
				List<Map<String,Object>> listFormControl=formControlService.selectByFormId(formId);
				List<Map<String,Object>> listFormControlParams=formControlService.selectParamsByFormId(formId);
				List<Map<String,Object>> listFormSave=formSaveService.selectByFormId(formId);
				
				formDataMap.put("FormControl", listFormControl);
				formDataMap.put("FormControlParams", listFormControlParams);
				formDataMap.put("FormSave", listFormSave);
				
				
				//保存
				formData=JSON.toJSONString(formDataMap);
				model = new HashMap<String, Object>();
				model.put("formId", formId);
				model.put("formData", formData);
				model.put("isSync", 0);
				formService.update(model);
			}
			else
			{
				//请先保存Form
			}
			

			
			
			RenderPage.JsonByString(response, "1");
		} catch (Exception e) {
			ErrorLog.OnWrite(e);
		}

	}
	
	private void saveFormSave(String saveTableId,String saveTableName,String saveFieldId,String saveFieldName,String formId,String formControlId)
	{
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("saveType",2);
		paramMap.put("formId",formId);
		paramMap.put("formControlId",formControlId);
		List<Map<String, Object>> list = formSaveService.select(paramMap);
		
		List<Map<String, Object>> listFormSave2=new ArrayList<Map<String, Object>>();
		String[] saveFieldIdArray=saveFieldId.split(",");
		String[] saveFieldNameArray=saveFieldName.split(",");
		String[] saveTableIdArray=saveTableId.split(",");
		String[] saveTableNameArray=saveTableName.split(",");
		for(int i=0;i<saveFieldIdArray.length;i++)
		{
			if(saveTableIdArray[i].length()==0 && saveFieldIdArray[i].length()==0)
			{
				//处理选择后再清空的情况
				continue;
			}
			
			Map<String, Object> itemFormSave2=new HashMap<String, Object>();
			String id="";
			for(int j=0;j<list.size();j++)
			{
				if(list.get(j).get("SaveTableId").equals(saveTableIdArray[i]) && list.get(j).get("SaveFieldId").equals(saveFieldIdArray[i]))
				{
					id=list.get(j).get("Id").toString();
				}
			}
			
			itemFormSave2.put("Id", id);
			itemFormSave2.put("SaveType", 2);
			itemFormSave2.put("FormId", formId);
			itemFormSave2.put("FormControlId", formControlId);
			itemFormSave2.put("SaveTableId", saveTableIdArray[i]);
			itemFormSave2.put("SaveTableName", saveTableNameArray[i]);
			itemFormSave2.put("SaveFieldId", saveFieldIdArray[i]);
			itemFormSave2.put("SaveFieldName", saveFieldNameArray[i].split("\\.")[1]);
			listFormSave2.add(itemFormSave2);
		}
		
		BaseController.OnSaveList(SpringContextHolder.getBean(FormSaveService.class), listFormSave2, list, "Id","FormId","SaveType,FormControlId,SaveTableId,SaveTableName,SaveFieldId,SaveFieldName",false);
	}
	
	private void saveParams(List<Map<String,Object>> listFormParams,String formControlId,int formControlType)
	{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		int objectType=convertByFormControlType(formControlType);
		paramMap.put("objectType",objectType);
		paramMap.put("objectId",formControlId);
		List<Map<String, Object>> list = formParamsService.select(paramMap);
		
		BaseController.OnSaveList(SpringContextHolder.getBean(FormParamsValueService.class), listFormParams, list, "ParamsValueId","ObjectId","ParamsId,ParamsValue",true);
	}
	
	
	@RequestMapping(params = "method=delete", method = RequestMethod.POST)
	public void del(HttpServletRequest request, HttpServletResponse response) {
		try{
			String[] array = StringProcess.getRequest(request.getParameter("selectitem"), "").split(",");
			for (String formControlId : array) {
				if(formControlId.length()>0){
					formControlService.delete(formControlId);
				}
			}
	
			RenderPage.JsonByString(response, "1");
		}catch(Exception e){
			ErrorLog.OnWrite(e);
		}
		
	}
}
